package lzk.myshop.service.impl;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import lzk.myshop.Util.NewGoods;
import lzk.myshop.config.TencentCloudConfig;
import lzk.myshop.dao.GoodsMapper;
import lzk.myshop.service.TencentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class TencentImpl implements TencentService {
    @Autowired
    TencentCloudConfig tencentCloudConfig;
    @Autowired
    GoodsMapper goodsMapper;
    @Override
    public Map<String, Object> newGoods(NewGoods newGoods) throws IOException {
        COSClient cosClient = tencentCloudConfig.get();
        String fileName = newGoods.getFile().getOriginalFilename();
        // 获取文件后缀
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        // 若须要防止生成的临时文件重复,能够在文件名后添加随机码
        File file = File.createTempFile(fileName, prefix);
        newGoods.getFile().transferTo(file);
        // 指定文件将要存放的存储桶
        String bucketName = "onlineshop-1320925777";
        // 指定文件上传到 COS 上的路径，即对象键。例如对象键为 folder/picture.jpg，则表示将文件 picture.jpg 上传到 folder 路径下
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String timestamp = dateFormat.format(new Date());
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String key = "file_" + timestamp + "_" + uuid + ".jpg";
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file);
        ObjectMetadata objectMetadata= new ObjectMetadata();
        objectMetadata.setContentDisposition("inline"); // 设置 Content-Disposition 为 "inline"
        putObjectRequest.setMetadata(objectMetadata);
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        Date expiration = new Date(new Date().getTime() + 100L * 60L * 60L * 1000L);
        URL url = cosClient.generatePresignedUrl(bucketName, key, expiration);
        String u =url.toString();
        u = u.substring(0, u.indexOf("?"));
        newGoods.setImage(u);
        int i = goodsMapper.newGoods(newGoods);
        Map<String,Object> result = new HashMap<>();
        if (i==1){
            result.put("code",1);
            result.put("message","添加成功");
            result.put("date",null);
        }else {
            result.put("code",0);
            result.put("message","添加失败");
            result.put("date",null);
        }
        return result;
    }
}
